package demo;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author ：黄淼淳
 * @date ：2021/12/18 17:43
 * @description：并发控制信号灯
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        /*Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try{
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢到了车位！！！");
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName()+"离开了车位！！！");
                } catch (InterruptedException e){
                    e.printStackTrace();
                } finally{
                    semaphore.release();
                }
            },String.valueOf(i+1)).start();
        }*/
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 12; i++) {
            new Thread(()->{
                try{
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢到了");
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName()+"释放了");
                } catch (InterruptedException e){
                    e.printStackTrace();
                } finally{
                    semaphore.release();
                }
            },String.valueOf(i+1)).start();
        }
    }
}
